<template>
  <div class="params">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="注意：只允许选择三级分类商品" type="warning" :closable="false" show-icon></el-alert>
      <el-row>
        <el-col>
          <span>请选择分类商品:</span>
          <el-cascader
            v-model="cascaderValue"
            :options="cascaderList"
            :props="resultprops"
            clearable
            @change="handleChange"
            style="width:400px"
          ></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-row>
            <el-col>
              <el-button type="primary" :disabled="isDisabled" @click="addVisible = true">添加参数</el-button>
            </el-col>
          </el-row>
          <el-table :data="manyData" style="width: 100%" stripe border row-key="attr_id">
            <el-table-column type="expand" width="30">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="bianji(scope.row)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteRow(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-row>
            <el-col>
              <el-button type="primary" :disabled="isDisabled" @click="addVisible = true">添加属性</el-button>
            </el-col>
          </el-row>
          <el-table :data="onlyData" style="width: 100%" stripe border row-key="attr_id">
            <el-table-column type="expand" width="30">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="bianji(scope.row)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteRow(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog :title="'添加' + textName" :visible.sync="addVisible" width="30%" @close="addReset">
      <el-form :model="addForm" :rules="addRules" ref="ruleForm" label-width="100px">
        <el-form-item :label="textName" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParameter()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="'修改' + textName"
      :visible.sync="xiugaiVisible"
      width="30%"
      @close="xiugaiReset"
    >
      <el-form :model="xiugaiForm" :rules="xiugaiRules" ref="xiugaiForm" label-width="100px">
        <el-form-item :label="textName" prop="attr_name">
          <el-input v-model="xiugaiForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="xiugaiVisible = false">取 消</el-button>
        <el-button type="primary" @click="xiugaiParameter()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "params",
  data() {
    return {
      cascaderValue: [],
      cascaderList: [],
      resultprops: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
      },
      activeName: "many",
      myid: null,
      manyData: [],
      onlyData: [],
      addVisible: false,
      addForm: {
        name: "",
      },
      addRules: {
        name: [{ required: true, message: "请输入...", trigger: "blur" }],
      },
      xiugaiVisible: false,
      xiugaiForm: {
        attr_name: "",
      },
      xiugaiRules: {
        attr_name: [{ required: true, message: "请输入...", trigger: "blur" }],
      },
    };
  },
  methods: {
    xiugaiReset() {
      this.$refs.xiugaiForm.resetFields();
    },
    bianji(row) {
      this.$http
        .get(`categories/${this.myid}}/attributes/${row.attr_id}`, {
          params: { attr_sel: this.activeName },
        })
        .then((res) => {
          if (res.data.meta.status !== 200) {
            return this.$message.error("加载失败");
          }
          this.xiugaiForm = res.data.data;
          console.log(res.data.data.attr_name);
        });
      this.xiugaiVisible = true;
    },
    xiugaiParameter() {
      this.$refs.xiugaiForm.validate((validate) => {
        this.$http
          .put(
            `categories/${this.myid}/attributes/${this.xiugaiForm.attr_id}`,
            { attr_name: this.xiugaiForm.attr_name, attr_sel: this.activeName }
          )
          .then((res) => {
            if (res.data.meta.status !== 200) {
              return this.$message.error("修改失败");
            }
            this.$message.success("修改成功");
            this.getdeta();
            this.xiugaiVisible = false;
          });
      });
    },
    deleteRow(row) {
      this.$confirm("此操作将永久删除该参数, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http
            .delete(`categories/${this.myid}/attributes/${row.attr_id}`)
            .then((res) => {
              if (res.data.meta.status !== 200) {
                return this.$message.error("删除失败");
              }
              this.getdeta();
              this.$message.success("删除成功");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleChange(value) {
      if (value.length !== 3) {
        this.cascaderValue = [];
        this.manyData = [];
        this.onlyData = [];
        return this.$message.info("请选择三级分类");
      }
      this.myid = value[value.length - 1];
      this.getdeta();
    },
    getcascaderList() {
      this.$http.get("categories").then((res) => {
        if (res.data.meta.status !== 200) {
          return this.$message.error("数据获取失败");
        }
        this.cascaderList = res.data.data;
      });
    },
    getdeta() {
      //console.log(this.myid);
      this.$http
        .get(`categories/${this.myid}/attributes`, {
          params: { sel: this.activeName },
        })
        .then((res) => {
          //console.log(res)
          if (res.data.meta.status !== 200) {
            return this.$message.error("加载数据失败");
          }
          let myData = res.data.data;
          myData.forEach((item) => {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
            item.inputVisible = false;
            item.inputVisible = "";
          });
          if (this.activeName == "many") {
            this.manyData = myData;
            console.log(this.manyData);
          } else {
            this.onlyData = myData;
            console.log(this.onlyData);
          }
        });
    },
    handleClick(tab, event) {
      //console.log(tab.name);
      if (this.cascaderValue.length !== 3) {
        return;
      }
      this.getdeta();
    },
    addReset() {
      this.$refs.ruleForm.resetFields();
    },
    addParameter() {
      this.$refs.ruleForm.validate((validate) => {
        if (!validate) return;
        this.$http
          .post(`categories/${this.myid}/attributes`, {
            attr_name: this.addForm.name,
            attr_sel: this.activeName,
          })
          .then((res) => {
            if (res.data.meta.status !== 201) {
              return this.$message.error("添加参数失败");
            }
            this.$message.success("添加参数成功");
            this.getdeta();
          });
        this.addVisible = false;
      });
    },
    handleClose(index, row) {
      row.attr_vals.splice(index, 1);
      this.$http
        .put(`categories/${this.myid}/attributes/${row.attr_id}`, {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(" "),
        })
        .then((res) => {
          if (res.data.meta.status !== 200) {
            return this.$message.error("删除失败");
          }
          this.$message.success("删除成功");
        });
    },
    handleInputConfirm(row) {
      if (row.inputValue) {
        row.attr_vals.push(row.inputValue);
      } else {
        row.inputVisible = false;
        return;
      }

      row.inputVisible = false;
      row.inputValue = "";
      this.$http
        .put(`categories/${this.myid}/attributes/${row.attr_id}`, {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(" "),
        })
        .then((res) => {
          if (res.data.meta.status !== 200) {
            return this.$message.error("添加失败");
          }
          this.$message.success("添加成功");
        });
    },
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
  },
  computed: {
    isDisabled() {
      if (this.cascaderValue.length !== 3) {
        return true;
      }
      return false;
    },
    textName() {
      if (this.activeName == "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    },
  },
  mounted() {
    this.getcascaderList();
  },
};
</script>

<style scoped>
.el-breadcrumb {
  margin-bottom: 20px;
}
.el-row {
  margin-bottom: 10px;
  margin-top: 15px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>
